package com.samnative.pineapple.main;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.PutFileUtils;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.makeramen.roundedimageview.RoundedImageView;
import com.samnative.pineapple.widget.CityPicker;
import com.shashank.sony.fancytoastlib.FancyToast;
import com.yalantis.ucrop.UCrop;
import com.samnative.pineapple.entity.AliPostImginfoModel;
import com.samnative.pineapple.entity.UserModel;
import com.samnative.pineapple.http.HttpRequest;
import com.samnative.pineapple.http.JsonResult;
import com.samnative.pineapple.instance.AppPrefer;
import com.samnative.pineapple.utils.GlideRequestOptions;
import com.samnative.pineapple.value.Config;
import com.samnative.pineapple.widget.LoadingDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.nereo.multi_image_selector.MultiImageSelector;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;


public class MyInfoActivity extends BaseActivity implements OnClickListener, EasyPermissions.PermissionCallbacks {

    /**
     * 用户头像
     */
    private RoundedImageView ivUserHead;
    /**
     * 昵称显示框
     */
    private TextView tv_nickname;
    private TextView tv_username;
    private TextView tv_address;
    /**
     * 用户信息
     */
    private UserModel userModel;

    private CityPicker cityPicker;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_info;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        initView();
    }

    private void initView() {
        find(R.id.back_btn).setOnClickListener(this);
        find(R.id.head_layout).setOnClickListener(this);
        find(R.id.rl_change_nickname).setOnClickListener(this);
        find(R.id.rl_address).setOnClickListener(this);

        ivUserHead = find(R.id.user_head_iv);
        tv_nickname = find(R.id.tv_nickname);
        tv_username = find(R.id.tv_username);
        tv_address = find(R.id.tv_address);

        userModel = AppPrefer.getUserModel(mContext);
        cityPicker = new CityPicker(mContext);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.back_btn:
                finish();
                break;
            case R.id.head_layout:
                if (EasyPermissions.hasPermissions(mContext, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                    MultiImageSelector.create()
                            .showCamera(true) // show camera or not. true by default
                            .single() // single mode
                            .start(MyInfoActivity.this, 100);
                } else {
                    EasyPermissions.requestPermissions(MyInfoActivity.this, "\"" + getString(R.string.app_name)
                                    + "\"需要获取相关权限才能正常使用,请确认",
                            12, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE);
                }
                break;
            case R.id.rl_change_nickname:
                startActivity(new Intent(mContext, NicknameActivity.class));
                break;
            case R.id.rl_address:
                cityPicker.showCityPicker();
                cityPicker.setOnChangeCity(new CityPicker.OnChangeCity() {
                    @Override
                    public void callCityInfo(String province, String city, String county, String areacode) {
                        String f_city = province + "-" + city + "-" + county;
                        tv_address.setText(f_city);
                        userModel.getData().setAddress(f_city);

                        changePersonData();
                    }
                });
                break;
        }
    }

    /**
     * 获取用户信息
     */
    public void showUserInfo() {
        if (AppPrefer.getInstance(mContext).getString(AppPrefer.mtoken, "").isEmpty()) {
            return;
        }
        Map<String, String> map = new HashMap<>();
        HttpRequest.request(this, "/client/user/userinfo", "", map, "POST", new JsonResult() {
            @Override
            public void reqestSuccess(JSONObject result) {
                // TODO Auto-generated method stub
                try {
                    AppPrefer.getInstance(mContext).put(AppPrefer.userinfo, result.toString());
                    showData();
                } catch (Exception e) {
                    // TODO: handle exception
                    e.printStackTrace();
                }
            }

        });
    }

    /**
     * 显示数据
     */
    private void showData() {
        // TODO Auto-generated method stub
        userModel = AppPrefer.getUserModel(mContext);
        if (userModel == null) {
            return;
        }

        Glide.with(mContext)
                .load(Config._API_URL + userModel.getData().getHeadicon()) //图片地址
                .apply(GlideRequestOptions.DEFAULT_HEAD)
                .into(ivUserHead);

        tv_username.setText(userModel.getData().getUsername());
        tv_nickname.setText(userModel.getData().getNickname());
        tv_address.setText(userModel.getData().getAddress());
    }


    private void changePersonData() {
        try {
            JSONObject json = new JSONObject();

            String result = new Gson().toJson(userModel.getData());
            JSONObject jinfo = new JSONObject(result);

            json.put("userinfo", jinfo);

            HttpRequest.request(this, "/client/user/upuserinfo", "", String.valueOf(json), "POST", new JsonResult() {
                @Override
                public void reqestSuccess(JSONObject result) {
                    FancyToast.showToast(mContext, "修改成功", FancyToast.SUCCESS, false);
                    showUserInfo();
                }
            });

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100 && resultCode == RESULT_OK) {
            List<String> mSelectPath = data
                    .getStringArrayListExtra(MultiImageSelector.EXTRA_RESULT);
            // 初始化UCrop配置
            UCrop.Options options = new UCrop.Options();
            options.setCompressionFormat(Bitmap.CompressFormat.JPEG);
            options.setCompressionQuality(100);
            options.setHideBottomControls(true);
            options.setToolbarColor(0xff202728);
            options.setToolbarWidgetColor(0xffffffff);
            options.setStatusBarColor(0xff000000);

            File newFile = new File(mContext.getCacheDir().getAbsoluteFile() + Config.SaveImgPath + "info_head.jpg");
            //图片存在就删除掉
            if (newFile.getAbsoluteFile().exists()) {
                newFile.delete();
            }

            //保存的目标目录不存在就创建目录
            if (!newFile.getParentFile().exists()) {
                newFile.getParentFile().mkdirs();
            }

            UCrop.of(Uri.fromFile(new File(mSelectPath.get(0))),
                    Uri.fromFile(newFile))
                    .withOptions(options).withAspectRatio(1, 1)
                    .withMaxResultSize(520, 520).start(this);
        }

        if (requestCode == UCrop.REQUEST_CROP) {
//            LoadingDialog.getInstance(mContext).show();
//            getPostImgInfo(new File(mContext.getCacheDir().getAbsoluteFile() + Config.SaveImgPath + "info_head.jpg").getPath(),
//                    new Handler.Callback() {
//                        @Override
//                        public boolean handleMessage(Message msg) {
//                            if (msg.what == 200) {
//                                postUserHead();
//                            } else {
//                                FancyToast.showToast(mContext, "图片上传失败", FancyToast.WARNING, false);
//                            }
//                            return false;
//                        }
//                    });

            HttpRequest.postImage(this, "/movie/api/upload", "",
                    mContext.getCacheDir().getAbsoluteFile() + Config.SaveImgPath + "info_head.jpg", new JsonResult() {
                        @Override
                        public void reqestSuccess(JSONObject result) {
                            String url = result.optString("url");
                            if (!url.isEmpty()) {
//                                FancyToast.showToast(mContext, "图片上传成功", FancyToast.SUCCESS, false);

                                userModel.getData().setHeadicon(url);
                                changePersonData();

                            }
                        }
                    });

        }
    }


    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        if (EasyPermissions.hasPermissions(mContext, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            MultiImageSelector.create(mContext)
                    .showCamera(true) // show camera or not. true by default
                    .single() // single mode
                    .start(MyInfoActivity.this, requestCode);
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        /**
         * 若是在权限弹窗中，用户勾选了'NEVER ASK AGAIN.'或者'不在提示'，且拒绝权限。
         * 这时候，需要跳转到设置界面去，让用户手动开启。
         */
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).build().show();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }


    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        showUserInfo();
    }
}
